package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.RequiredArgsConstructor;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    private final StringRedisTemplate stringRedisTemplate;
    private final CacheClient cacheClient;
    //定义线程池解决缓存击穿问题
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        //queryWithPassThough(id);  解决缓存穿透
        Shop shop = cacheClient.queryWithPassThough(CACHE_SHOP_KEY, id, Shop.class, this::getById,
                CACHE_SHOP_TTL, TimeUnit.MINUTES);
       // cacheClient.setWithLogicalExpire(CACHE_SHOP_KEY + id, this::getById CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //利用互斥锁解决缓存击穿问题
        //return Result.ok(queryWithMutex(id));
        //利用逻辑过期解决缓存击穿问题
        //return Result.ok(queryWithLogicalExpire(id));
        /*Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById,
                CACHE_SHOP_TTL, TimeUnit.MINUTES);*/
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);

    }
    @Override
    @Transactional
    public Result update(Shop shop) {
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        //返回结果
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //判断参数x，y是否存在
        if (x==null || y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //查询redis中的数据
        //2.1计算分页参数
        int from = (current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current*SystemConstants.DEFAULT_PAGE_SIZE;
        //查询redis中的数据
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );

        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        //解析出id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size()<=from){
            //没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //截取from-end进行分页
        ArrayList<Object> ids = new ArrayList<>(list.size());
        Map<String,Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            //获取店铺id
            String shopId = result.getContent().getName();
            ids.add(Long.valueOf(shopId));
           //获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopId,distance);
        });
        //查询店铺数据
        String join = StrUtil.join(",", ids);
        List<Shop> shopList = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        for (Shop shop : shopList) {
            //设置距离
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shopList);
    }

    //逻辑过期解决缓存击穿问题
    private Shop queryWithLogicalExpire(Long id) {
        /**
         * 注：因为使用逻辑过期解决缓存穿透问题的应用场景一般都是先将数据写入redis中，即缓存预热
         * 所以当redis中没有数据时，直接返回null值即可，不需要判断是否为空然后查询数据库的情况，即不需要考虑缓存击穿
         * */
        //1.从redis中查询数据
        String key= CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.如果为空直接返回null，不用进行下一步判断
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        //反序列化为RedisData对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Object dataShop = redisData.getData();
        Shop shop = JSONUtil.toBean((JSONObject) dataShop, Shop.class);
        //3.1.判断是否逻辑时间过期
        if(LocalDateTime.now().isAfter(redisData.getExpireTime())){
            //3.2如果未过期，直接返回数据
            return shop;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        //3.3.过期，获取锁
        boolean islock = tryLock(lockKey);
        //3.3.加锁失败，返回旧数据
        if(!islock){
            return shop;
        }
        //3.4.加锁成功，新建线程查询数据库,并加入缓存
        CACHE_REBUILD_EXECUTOR.submit(()->{
            try {
                this.saveShop2Redis(id,30L);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                unLock(lockKey);
            }
        });
        return shop;
    }


    //缓存穿透解决方法
    public Shop queryWithPassThough(Long id){
        //1.从redis缓存中读取数据,如果redis中没有数据，那么返回的时null不是空字符串
        String key= CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.如果存在直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            return  JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断redis是否为null，如果不为null，返回空信息
        if(shopJson != null){
            return null;
        }
        //3.不存在，从数据库中查询数据
        Shop shop = lambdaQuery().eq(Shop::getId, id).one();
        //4.不存在，将控制存储在redis中，防止缓存穿透，并且设置超时时间为2min
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //5.存在，返回结果，并将结果写入redis缓存中,并设置超时时间为10分钟
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }
      //互斥锁解决缓存击穿问题
    public Shop queryWithMutex(Long id){
        //1.从redis缓存中读取数据,如果redis中没有数据，那么返回的时null不是空字符串
        String key= CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.如果存在直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            return  JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断redis是否为null，如果不为null，返回空信息
        if(shopJson != null){
            return null;
        }
        //3.1如果不存在，获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean flag = tryLock(lockKey);
            //3.2判断是否获取到锁
            if(!flag){
                //3.3获取不到锁，休眠等待
                Thread.sleep(50);
                return  queryWithMutex(id);
            }
            //3.4获取到锁，查询数据库,双重检验
            if (StrUtil.isNotBlank(shopJson)) {
                return  JSONUtil.toBean(shopJson, Shop.class);
            }
            //3.不存在，从数据库中查询数据
            shop = lambdaQuery().eq(Shop::getId, id).one();
            //4.不存在，将控制存储在redis中，防止缓存穿透，并且设置超时时间为2min
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //5.存在，返回结果，并将结果写入redis缓存中,并设置超时时间为10分钟
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //释放锁
            unLock(lockKey);
        }
        return shop;
    }
    public boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    public void unLock(String key){
        stringRedisTemplate.delete(key);
    }
    private void saveShop2Redis(Long id,Long expireMinutes){
        //根据查询数据库
        String key= CACHE_SHOP_KEY + id;
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusMinutes(expireMinutes));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));

    }
}
